/*
 * Created on Mar 3, 2004
 */
package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.util.LabelValueBean;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.SalesInfo;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.ConfigManager;

/**
 * @author Ravikanth
**/
public class GeneratePackingSlipAction  extends ChipTrackAction
{
	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception 
	{
		HttpSession session = request.getSession();
        User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
        HashMap errors		= new HashMap();
		String returnVal 	= "failure";
		String action 		= request.getParameter( "action" );
		int total			= 0;
		boolean dropShip	= false;
		String salesOrderId = ""; 
		String vendorLocationId	= "";
		
		PackingSlipForm packingSlipForm 		=  null; 
		ArrayList packingSlipListBySalesOrderId = new ArrayList(0);
		HashMap customerShippingLineItemMap		= new HashMap(0); 
		HashMap orderLineItemMap 				= new HashMap(0);
		ArrayList repetedPartNumber 			= new ArrayList();
		ArrayList lineItemList 					= new ArrayList();
        ArrayList holdLineItemList 					= new ArrayList();

		// This is the Attibute Containing the Final Inventory Pulled
		session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
		// This is the Attribute Identifying if there are any part numbers repeating the PS
		session.removeAttribute( "repetedPartNumber" );
		// This is attribute usefull for maintaining the consistance in Final Inventory screen
		session.removeAttribute( "orgFinalInventoryDataList" );
		
		try
		{
			salesOrderId 		= request.getParameter ( "salesOrderId" );
			vendorLocationId	= request.getParameter ( "vendorLocationId" );
            //Location location = VendorDAO.getLocationByAddressId(Integer.parseInt(vendorLocationId), Constants.LOCATION_TYPE_FINISHED_GOODS ) ;
            String vendorLocationName = VendorDAO.getLocationByAddressId( Integer.parseInt(vendorLocationId), Constants.LOCATION_TYPE_FINISHED_GOODS );

            request.setAttribute( "vendorLocationName", vendorLocationName );
            request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
			request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
        
            // Check wether drop shippment or Packinslip
			if( request.getParameter ( "dropShip" ) != null )
			{
				dropShip = request.getParameter ( "dropShip" ).equalsIgnoreCase("true") ? true : false;
			}
				 
			// Fetch the Sales Order Details
			SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );

			// Fetch the Number of Packing Slips previously generated for the Sales Order
			total = NewPackingSlipDAO.getTotalNumberOfPackingSlipsGenerated ( salesOrderId );

			// Fetch the Customer Details
			Customer customer = CustomerDAO.loadCustomerById (salesOrder.getCustomerId());
            CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
			// Fetch Contact Person details
			//String shippingContactPerson = NewPackingSlipDAO.getShippingOrBillingContactPerson ( null, salesOrderId );
            String shippingContactPerson = salesOrder.getShippingContactPerson();

			// Fetch the Shipping Method
			String shippedVia = "";
			if ( ( salesOrder.getShippingMethod() != null ) && ( salesOrder.getShippingMethod().trim().length() != 0 ) ) 
			{
				shippedVia = salesOrder.getShippingMethod().trim();
			} 
			else
			{
				shippedVia = "";
			}

            //Added by Rohan on July 22nd 2004
            SalesInfo salesInfo = UserDAO.getSalesOrderInfo( null );
            StringBuffer packingSlipNumber = new StringBuffer( String.valueOf( total + 1 ) );

            //adding zeroes to the packing slip number at the start to increase the length to the
            //value specified in the sales setup screen
            for( int i = packingSlipNumber.length(); i < salesInfo.getPsLength(); i++ )
            {
                packingSlipNumber.insert( 0, "0" );
            }

            //Added by Rohan on July 23rd 2004
            if( "".equals( salesInfo.getPsPrefix() ) )
            {
                packingSlipNumber.insert( 0, salesOrder.getSalesOrderNo() + "-" );
            }
            else
            {
                packingSlipNumber.insert( 0, salesInfo.getPsPrefix() + "-" + salesOrder.getSalesOrderNo() + "-" );
            }
            //End of additions by Rohan on July 23rd 2004
            String invoiceNo = "";//PackingSlipDAO.getNextPsInvoiceNumber();
            // Create an instance of PackingSlipForm
			packingSlipForm = new PackingSlipForm (
											  //"PS-" + salesOrder.getSalesOrderNo() + "-" + (total + 1),
                                              packingSlipNumber.toString(), //Modified by Rohan on July 22nd 2004
											  -1,
											  salesOrder.getSalesOrderId(),
											  salesOrder.getSalesOrderNo(),
											  salesOrder.getCustomerName(),
											  salesOrder.getCustomerPO(),
											  shippingContactPerson, 
											  salesOrder.getRegionalRep(),
											  customer.getTerms(),
											  salesOrder.getDeliveryTerms(),
											  null,
											  new String[]{""},
											  shippedVia,
											  salesOrder.getShippingMethod(),
											  salesOrder.getShippingAccount(),
											  salesOrder.getBillingAddress(),
											  salesOrder.getShippingAddress(),
											  salesOrder.getShippingInstructions() ,
				                              salesOrder.getComments(),
                                              salesOrder.getBillingAddressAsObject(),
				                              salesOrder.getShippingAddressAsObject() );

            packingSlipForm.setFreightInstructions( salesOrder.getFreightInstructions() );
			//System.out.println ( "GeneratePS:134 : >> " + salesOrder.getShippingAddressAsObject() );
			packingSlipForm.setStatus( "OPEN" );
			packingSlipForm.setShippingToAddressId ( salesOrder.getShippingAddressId() );
			packingSlipForm.setShipDate ( StringUtils.formatDateToString ( new Date(System.currentTimeMillis() ) ) );
			packingSlipForm.setShippingFromAddressId( Integer.parseInt( vendorLocationId ) );
            packingSlipForm.setShippingFromLocationId( Integer.parseInt( vendorLocationId ) ); // Added by Krishna Prasad on 27 May 2004
			packingSlipForm.setDropShippment( dropShip );
			packingSlipForm.setAction( action );
            packingSlipForm.setCustomerNumber( salesOrder.getCustomerNumber() ); // Added by Krishna Prasad on 17 June 2004
            packingSlipForm.setSupplierNumber( customer.getSupplierNumber() );
            packingSlipForm.setOdm(salesOrder.getOdm());
            packingSlipForm.setInvNo( invoiceNo );
            packingSlipForm.setIsSample( salesOrder.getIsSample());
            packingSlipForm.setConsignment( "0".equals( salesOrder.getIsConsignmentSales() ) );

            int odmId = salesOrder.getOdmId();
            if ( odmId > 0 )
            {
                customer.setCustomerId(salesOrder.getOdmId());
                CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
                packingSlipForm.setOdmSupplierNumber( customer.getSupplierNumber() );
                packingSlipForm.setOdmId( salesOrder.getOdmId() );
            }
            else
            {
                 packingSlipForm.setOdmSupplierNumber( "" );
            }
            String scheduledBefore = null;
            if ( user != null && user.getUserType() != Constants.USER_TYPE_CHIPTRAC ) //EXTERNAL USER
            {
                Calendar cal = Calendar.getInstance();
                cal.add ( Calendar.DATE, ConfigManager.getGeneratePSScheduledUptoDays() );
                scheduledBefore = StringUtils.formatDateToString( cal.getTime() );
            }
            // Fetch the LineItems That are Approved
			lineItemList = NewPackingSlipDAO.loadLineItemDetails( Integer.parseInt( salesOrderId), Integer.parseInt( vendorLocationId ), "APPROVED", scheduledBefore);
			packingSlipForm.setLineitems( lineItemList );

            // Fetch the  LineItems That are Hold
            holdLineItemList = NewPackingSlipDAO.loadLineItemDetails( Integer.parseInt( salesOrderId), Integer.parseInt( vendorLocationId ), "HOLD", null);

			// Fetch all the previous PackingSlips For the Sales Order
			packingSlipListBySalesOrderId = NewPackingSlipDAO.loadPackingSlipsBySalesOrderId ( Integer.parseInt( salesOrderId ), Constants.CUSTOMER_SHIPPING_STATUS_ISSED );

			// Fetch the repetedPartNumber. This is usefull when we pull data in Final Inventory screen
			// This will help to reduce the quantity pulled from one lineitem to the next lineitem
			repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( lineItemList );
			returnVal = "success";
		}
		catch ( ScalarException se )
		{
			if ( se.getRootCause().getMessage().indexOf ( "No Line Items are pending" ) != -1 )
			{
				errors.put ( "Sales order ID", "There are no pending line items to be shipped. Please select another Sales Order ID" );
			}
			else
			{
				errors.put ( "Sales order ID", "Unable to load this sales order ID data <br>Please select another Sales Order ID" );
			}
            System.out.println(" #### Errors " + se);
		}

		request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
		if( returnVal.equalsIgnoreCase("success") )
		{
	        request.setAttribute ( "packingSlipListBySalesOrderId",  setPackingSlipOrder ( packingSlipListBySalesOrderId , packingSlipForm.getLabel() ) );
            request.setAttribute ( "HoldLineItemList", holdLineItemList );
			session.setAttribute ( "packingSlipForm", packingSlipForm );
			if( repetedPartNumber.size() > 0 )
			{
				session.setAttribute( "repetedPartNumber", repetedPartNumber );
			}				
		}
		return ( mapping.findForward ( returnVal ) );
	}
  
  // Added by Neelima on 27-04 -2004
	private ArrayList setPackingSlipOrder ( ArrayList packingSlipListBySalesOrderId , String currentLabel )
	{
		ArrayList   packingSlipListBySalesOrderId1 = new ArrayList();
	    try
		{	 
			Iterator packingSlip = packingSlipListBySalesOrderId.iterator();				

			while ( packingSlip.hasNext() )
		 	{
				LabelValueBean packingSlipId = ( LabelValueBean )packingSlip.next();  
				String label = packingSlipId.getLabel();
				if ( ! label.equalsIgnoreCase( currentLabel ) )
				{
					packingSlipListBySalesOrderId1.add( packingSlipId );				   
				}
			}
		}
		catch ( Exception e )
		{
			System.out.println (e);
		}
		return packingSlipListBySalesOrderId1;
	} 
}